library(readxl)
library(ggplot2)
library(tidyverse)


fpth <- "main_model.csv"


tmp <- excel_sheets(fpth)
tmp <- tmp[2:length(tmp)]
df <- list()
phi_del <- read_excel(fpth) 
counter <- 0
for (sn in tmp) {
    counter <- counter + 1
    df1 <- read_excel(fpth, sheet = sn, col_names = F, col_types = "numeric")
    df1 <- df1[1:15, ]
    names(df1) <- paste0("del_", 1:15)
    df1$phi_qt <- rownames(df1)
    df1 <- df1 %>% 
        pivot_longer(cols = starts_with('del_'),
            names_to = 'del_qt', values_to = sn)
    df1$del_qt <- as.numeric(gsub("del_", "", df1$del_qt))
    df[[counter]] <- df1
}
df <- df %>% reduce(inner_join, by = c("del_qt", "phi_qt"))
df$del_qt <- as.numeric(df$del_qt)
df$phi_qt <- as.numeric(df$phi_qt)
phi_del$qt <- 1:15

df <- merge(df, phi_del[, c("phi", "qt")], by.x = "phi_qt", by.y = "qt")
df <- merge(df, phi_del[, c("del", "qt")], by.x = "del_qt", by.y = "qt")

df <- df %>% rowwise() %>% mutate(m = max(c(prob_inlanddomestic, prob_inlandexporter, prob_coastdomestic, prob_coastexporter)))

df$type <- "Exit"
df$type[df$prob_inlanddomestic == df$m & df$m != 0] <- "Periphery-Domestic"
df$type[df$prob_inlandexporter == df$m & df$m != 0] <- "Periphery-Exporter"
df$type[df$prob_coastdomestic == df$m & df$m != 0] <- "Core-Domestic"
df$type[df$prob_coastexporter == df$m & df$m != 0] <- "Core-Exporter"



ordered_leg <- c("Exit", "Periphery-Domestic", "Periphery-Exporter", "Core-Domestic", "Core-Exporter")

df$m[df$type == "Exit"] <- 0.8
ggplot(df, aes(del_qt, phi_qt, size = m, shape = type, color = type)) +
    geom_point(alpha = 0.9, stroke = 3) + scale_size(range = c(0, 15)) +
    scale_color_manual(values = c("#33a02c" , "#fb9a99", "black", "#1f78b4", "#b2df8a", "#a6cee3"),
        breaks = ordered_leg) +
    scale_shape_manual(values = c(4, 1, 7, 0, 2), breaks = ordered_leg) +
    theme_bw() + guides(size = "none") +
    labs(x = "Size", y = "Efficiency", shape = NULL, color = NULL) +
    theme(legend.position = "bottom", text=element_text(size=20))
ggsave("combined_example_qt.svg", device = "svg", dpi = 320)




ggplot(df, aes(phi_qt, del_qt, size = prob_inlanddomestic)) +
    geom_point(alpha = 0.5, shape = 20, show.legend  = F) +
    scale_size(range = c(0, 40))
ggsave("inlanddomestic_example.png")


ggplot(df, aes(phi_qt, del_qt, size = prob_inlandexporter)) +
    geom_point(alpha = 0.5, shape = 20) +
    scale_size(range = c(0, 40)) + 
    theme_minimal() +
    theme(legend.position = "bottom") 

ggsave("inlandexporter_example.png")
